package com.ias.agdis_r.volley;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.json.JSONObject;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;

/**
 * 发送Map数据并返回Map结果
 * 
 * @author Chipor
 *
 */
public class MapRequest extends JsonRequest<Map<String, Object>> {

	public MapRequest(int method, String url, JSONObject jsonRequest,
			Listener<Map<String, Object>> listener, ErrorListener errorListener) {
		super(method, url, (jsonRequest == null) ? null : jsonRequest
				.toString(), listener, errorListener);
	}

	public MapRequest(String url, JSONObject jsonRequest,
			Listener<Map<String, Object>> listener, ErrorListener errorListener) {
		this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,
				listener, errorListener);
	}

	public MapRequest(int method, String url, Map<String, Object> jsonRequest,
			Listener<Map<String, Object>> listener, ErrorListener errorListener) {
		this(method, url, (jsonRequest == null) ? null : new JSONObject(
				jsonRequest), listener, errorListener);
	}

	public MapRequest(String url, Map<String, Object> jsonRequest,
			Listener<Map<String, Object>> listener, ErrorListener errorListener) {
		this(url, new JSONObject(jsonRequest), listener, errorListener);
	}

	@Override
	protected Response<Map<String, Object>> parseNetworkResponse(
			NetworkResponse response) {
		try {
			String jsonString = new String(response.data,
					HttpHeaderParser.parseCharset(response.headers,
							PROTOCOL_CHARSET));
			return Response.success(JSONUtil.parseJsontoMap(jsonString),
					HttpHeaderParser.parseCacheHeaders(response));
		} catch (UnsupportedEncodingException e) {
			return Response.error(new ParseError(e));
		}
	}

}
